package com.sinosoft.hydra.um;

import cn.com.sinux.spring.commons.TreeNodeHelper;
import cn.com.sinux.spring.utils.TreeNodeUtils;
import cn.com.sinux.spring.utils.ValidatorUtils;
import com.sinosoft.hydra.um.domain.permission.SysOrganization;
import com.sinosoft.hydra.um.domain.permission.SysResource;
import com.sinosoft.hydra.um.domain.permission.SysUserMember;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-3-14
 * Time: 下午12:23
 * To change this template use File | Settings | File Templates.
 */
public class LoginUser extends SysUserMember implements Serializable, Cloneable {

    private String clientIp;

    public static String LOGIN_USER_KEY = "user.login.session.key";

    public String getClientIp() {
        return clientIp;
    }

    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    public static LoginUser createLoginUser(SysUserMember sysUserMember) {
        if (sysUserMember == null) {
            return null;
        }
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUserMember, loginUser);
        return loginUser;
    }

    public boolean hasPermission(String permission) {
        Subject subject = SecurityUtils.getSubject();
        return subject.isPermitted(permission);
    }

    public Object clone() {
        LoginUser user = null;
        try {
            user = (LoginUser) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return user;
    }

    private void sort(List<SysResource> resources){
        Collections.sort(resources, new Comparator<SysResource>() {

            public int compare(SysResource sysResource, SysResource sysResource2) {
                return sysResource2.getOrderNo().compareTo(sysResource.getOrderNo());
            }
        });
        for(SysResource sysResource : resources){
            if(ValidatorUtils.isArrayNotEmpty(sysResource.getChildren())){
                sort(sysResource.getChildren());
            }
        }
    }

    public List<SysResource> getMenuTree() {
        List<SysResource> resources = getMenu();
        for(SysResource sysResource : resources){
            sysResource.setSysResource(null);
            sysResource.setChildren(null);
        }
        resources =  TreeNodeUtils.buildTree(resources, new TreeNodeHelper<SysResource>(new TreeNodeHelper.TreeNodeParentHelper<SysResource>() {

            public String getParentId(SysResource sysResource) {
                return sysResource.getParentId();
            }
        }));
        sort(resources);
        return resources;
    }
}
